const util = require("../../utils/util")
const db = wx.cloud.database({
    env: 'work1-0g1b3grp436e9236'
})

Page({

    /**
     * 页面的初始数据
     */
    data: {
        companyImg: '',
        companyName: '',
        averageSalary: 0,
        address: '',
        isCloseToMap: false,
        introduce: '',
        category: '',
        fileList: [],
        companyCategoryList: [
            '农业相关','林业相关','畜牧业相关','渔业相关','机械与自动化相关','电商与运输', '其他'
        ],
        showCategory: false,
        // 判断图片是否上传完毕
        isUploaded: false,
        isPreUp: false
    },

    toShowCategoryList() {
        this.setData({showCategory: true})
    },

    onCloseCategoryList() {
        this.setData({showCategory: false})
    },

    onConfirmCategory(e) {
        console.log(e.detail.value)
        this.setData({category: e.detail.value, showCategory: false})
    },

    // 上传图片
    afterRead(event) {
        const { file } = event.detail;
        this.setData({isPreUp: true})
        this.setData({fileList: [{url: file.url, message: '上传中', deletable: true, status: 'uploading'}]})
        const filePath = 'companyImg/recruitment-company-img-' + new Date().getTime()+'.png'
        wx.cloud.uploadFile({
            cloudPath: filePath, // 上传至云端的路径
            filePath: file.url, // 小程序临时文件路径
            success: res => {
                // 返回文件 ID
                // console.log("上传成功",res)
                //获取文件路径
                const { fileList = [] } = this.data;
                fileList.push({ ...file, url: res.data });
                this.setData({fileList})
                const imgPath = 'https://776f-work1-0g1b3grp436e9236-1311803114.tcb.qcloud.la/' + filePath
                // console.log('imgPath', imgPath)
                this.setData({fileList: [{url: imgPath, name: '上传图片', message: '上传成功', deletable: true, status: 'done'}]})
                this.setData({companyImg: imgPath, isUploaded: true})
                util.myToastNone('上传成功')
            }, fail(error) {
                console.log(error)
                this.setData({fileList: [{url: file.url, message: '上传失败', deletable: true, status: 'failed'}]})
            }
        })
    },

    // 删除图片
    deleteFileList() {
        this.setData({fileList: []})
        util.myToastNone('删除成功')
    },

    submit() {
        if (this.checkCompanyImg() && this.checkCompanyName() && this.checkAverageSalary() 
            && this.checkCategory() &&this.checkAddress() && this.checkIntroduce()) {
            // 原来就有
            if (this.data.companyId) {
                console.log(this.data.companyId)
                db.collection('work_company').doc(this.data.companyId).update({
                    data: {
                        companyImg: this.data.companyImg,
                        companyName: this.data.companyName,
                        averageSalary: this.data.averageSalary,
                        address: this.data.address,
                        introduce: this.data.introduce,
                        category: this.data.category
                    }
                }).then((res)=>{
                    // console.log(res)
                    util.myToastSuccess('保存成功')
                    wx.navigateBack({delta: 0})
                }).catch(()=>{
                    util.myToastError('保存失败，请重试')
                })
            } else {
                // 初次创建
                const userInfo = wx.getStorageSync('userInfo')
                db.collection('work_company').add({
                    data: {
                        companyImg: this.data.companyImg,
                        companyName: this.data.companyName,
                        averageSalary: this.data.averageSalary,
                        address: this.data.address,
                        introduce: this.data.introduce,
                        userId: userInfo.userId,
                        category: this.data.category
                    }
                }).then((res)=>{
                    // console.log(res)
                    util.myToastSuccess('保存成功')
                    wx.redirectTo({
                      url: '/pages/firm/firm?id=' + res._id,
                    })
                }).catch(()=>{
                    util.myToastError('保存失败，请重试')
                })
            }
        } else {
            util.myToastNone('请检查输入是否有误')
        }
    },

    async getCompanyInfo(id) {
        const res = await db.collection('work_company').doc(id).get()
        // console.log(res.data)
        this.setData({
            address: res.data.address,
            averageSalary: res.data.averageSalary,
            companyName: res.data.companyName,
            introduce: res.data.introduce,
            companyImg: res.data.companyImg,
            companyId: res.data._id,
            category: res.data.category,
            fileList: [{url: res.data.companyImg, name: '上传图片', deletable: true}]
        })
    },

    toMap() {
        this.setData({isCloseToMap: true})
        wx.navigateTo({
          url: '/pages/map/map',
        })
    },

    checkCompanyImg() {
        if (this.data.isPreUp) {
            if (this.data.isUploaded) {
                return true
            } else {
                util.myToastNone('请等待图片上传完毕')
                return false
            }
        }
        if(!this.data.companyName) {
            util.myToastNone('请添加图片')
            return false
        }
        return true
    },

    checkCompanyName() {
        if(!this.data.companyName) {
            this.setData({companyNameErr: '请填写公司名称'})
            return false
        }
        this.setData({companyNameErr: ''})
        return true
    },

    checkAverageSalary() {
        if(!this.data.averageSalary) {
            this.setData({averageSalaryErr: '请输入员工月均工资'})
            return false
        }
        this.setData({averageSalaryErr: ''})
        return true
    },

    checkCategory() {
        if(!this.data.category) {
            this.setData({categoryErr: '请选择公司分类'})
            return false
        }
        this.setData({categoryErr: ''})
        return true
    },

    checkAddress() {
        if(!this.data.address) {
            this.setData({addressErr: '请输入公司地址'})
            return false
        }
        this.setData({addressErr: ''})
        return true
    },

    checkIntroduce() {
        if(!this.data.averageSalary) {
            this.setData({introduceErr: '请输入公司介绍'})
            return false
        }
        this.setData({introduceErr: ''})
        return true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log('companyId', options.id)
        this.setData({companyId: options.id})
        if (options.id) {
            this.getCompanyInfo(options.id)
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      if (this.data.isCloseToMap) {
          const currentLocation = wx.getStorageSync('currentLocation')
          this.setData({address: currentLocation.address})
      }
      this.setData({isCloseToMap: false})
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})